<?php

declare(strict_types=1);

namespace App\Controller\Admin;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use App\Middleware\AdminMiddleware;
use App\Model\Image as ModelImage;
use App\Utils\StrUtils;

/**
 * @AutoController(prefix="/admin/image")
 * @Middlewares({
 *     @Middleware(AdminMiddleware::class)
 * })
 */
class Image extends AbstractController
{
    public function list() {
        $data = $this->request->all();
        $query = ModelImage::query();

        $query = $query->orderBy('id', 'desc');
        if (isset($data['page_size']) && $data['page_size'] <= 0) {
            $list = $query->get();
        }else{
            $list = $query->paginate($data['page_size'] ?? 20);
        }
        return $this->success($list);
    }

    public function deleteMany() {
        $this->validate([
            'ids' => 'required|array'
        ]);
        $ids = $this->request->input('ids');
        
        $toDelete = ModelImage::query()->whereIn('id', $ids)->get();
        foreach ($toDelete as $img) {
            try {
                unlink(BASE_PATH.'/public'.$img->url);
            }catch(\Exception $e) {}
        }

        $res = ModelImage::destroy($ids);
        return $this->success($res);
    }

    public function upload() {
        $this->validate([
            'file' => 'file|image'
        ]);

        $file = $this->request->file('file');

        if (!in_array($file->getMimeType(), [
            'image/jpeg',
            'image/png',
            'image/bmp',
            'image/tiff',
            'image/gif',
            'image/webp',
        ])) {
            return $this->error('文件类型不正确');
        }

        $uploadPath = '/storage/'.date('Ymd');
        $filePath = BASE_PATH.'/public'.$uploadPath;
        if (!file_exists($filePath)) {
            mkdir($filePath);
        }
        $savename = date('YmdHis').StrUtils::randDigit().'.'.$file->getExtension();
        $file->moveTo($filePath.'/'.$savename);
        if (!$file->isMoved()) {
            return $this->error();
        }

        $model = new ModelImage();
        $model->url = $uploadPath.'/'.$savename;
        $model->save();

        return $this->success($model);
    }
}
